package top.huhuiyu.springboot2.study.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.huhuiyu.springboot2.study.config.MxnzpConfig;
import top.huhuiyu.springboot2.study.entity.joke.Joke;
import top.huhuiyu.springboot2.study.entity.joke.TbJoke;
import top.huhuiyu.springboot2.study.mapper.joke.TbJokeMapper;
import top.huhuiyu.springboot2.study.service.TbJokeService;
import top.huhuiyu.springboot2.study.util.JsonUtils;

/**
 * @author 胡辉煜
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TbJokeServiceImpl implements TbJokeService {

  private final TbJokeMapper tbJokeMapper;
  private final RestTemplate restTemplate;

  @Override
  public Joke getJoke() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APP_ID);
    headers.add("app_secret", MxnzpConfig.APP_SECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    String result = restTemplate.exchange(MxnzpConfig.JOKE_RANDOM_URL, HttpMethod.GET, entity, String.class).getBody();
    log.debug("笑话信息：{}", result);
    Joke joke = JsonUtils.parse(result, Joke.class);
    return joke;
  }

  @Override
  public int saveJoke() {
    Joke joke = getJoke();
    joke.getData().forEach(data -> {
      TbJoke tbJoke = new TbJoke();
      tbJoke.setContent(data.getContent());
      tbJoke.setUpdateTime(data.getUpdateTime());
      tbJokeMapper.insert(tbJoke);
    });
    return joke.getData().size();
  }

}
